from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
import time

from web.forms import project
from web import models
from utils.tencent.tencent_cos import create_cos_bucket


def project_list(request):
    """项目列表"""
    if request.method == "GET":
        # GET请求，查看项目列表
        """
        1.从数据库中获取两部分数据
            我创建的所有项目：已星标、未星标
            我参与的所有项目；已星标、未星标
        2.提取已星标
            列表 = 循环 [我创建的所有项目] + [我参与的所有项目] 把已星标的数据提取
        """
        project_dict = {"star": [], "my": [], "join": []}

        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        # print(join_project_list.values_list("project__name"))
        # 循环添加
        for item in my_project_list:
            if item.star:
                project_dict['star'].append({"value": item, "type": "my"})
            else:
                project_dict['my'].append(item)

        for item in join_project_list:
            if item.star:
                project_dict['star'].append({"value": item.project, "type": "join"})
            else:
                project_dict['join'].append(item.project)

        form = project.ProjectForm(request)
        return render(request, 'project_list.html', {"form": form, "project_dict": project_dict})

    # POST请求，创建项目
    form = project.ProjectForm(request, data=request.POST)
    if form.is_valid():
        # 创建cos桶
        bucket_name = "{}-{}-1304822570".format(request.tracer.user.mobile_phone, int(time.time()))
        region = "ap-nanjing"
        create_cos_bucket(bucket_name, region)

        # 验证通过
        form.instance.creator = request.tracer.user
        form.instance.region = region
        form.instance.bucket = bucket_name
        # 创建项目
        instance = form.save()

        # 初始化项目问题类型(一创建项目就把项目问题的类型初始化为："任务", '功能', 'Bug')
        issue_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:  # ["任务", '功能', 'Bug']
            issue_type_object = models.IssuesType(project=instance, title=item)  # 创建一个问题类型
            issue_type_object_list.append(issue_type_object)

        models.IssuesType.objects.bulk_create(issue_type_object_list)  # 批量创建问题类型

        return JsonResponse({"status": True})

    return JsonResponse({"status": False, "err": form.errors})


def project_star(request, project_type, project_id):
    """添加星标项目"""
    if project_type == "my":
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)

    if project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)

    return redirect("project_list")


def project_unstar(request, project_type, project_id):
    """取消星标项目"""
    if project_type == "my":
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)

    if project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)

    return redirect("project_list")